package com.liqing.movecomment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liqing.movecomment.dao.*;
//import com.liqing.movecomment.elastic.LoadElasService;
import com.liqing.movecomment.entity.*;

import com.liqing.movecomment.enums.Constent;
import com.liqing.movecomment.entity.Move;
import com.liqing.movecomment.service.MoveService;
//import com.liqing.movecomment.util.ESUtils;
import com.liqing.movecomment.util.SwapePageUtil;
import com.liqing.movecomment.vo.MoveAddVo;
import com.liqing.movecomment.vo.MoveExcel;
import com.liqing.movecomment.vo.MoveVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import java.io.IOException;

import java.util.*;
import java.util.stream.Collectors;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import javax.annotation.Resource;


@Transactional
@Service("moveService")
public class MoveServiceImpl extends ServiceImpl<MoveDao, Move> implements MoveService {
    @SuppressWarnings("all")
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(MoveServiceImpl.class);
    @Resource
    private MoveDao moveDao;
    @Resource
    private TagDao tagDao;
    @Resource
    private ActorDao actorDao;
    @Resource
    private MoveTagDao moveTagDao;
    @Resource
    private MoveActorDao moveActorDao;
//    @Resource
//    private LoadElasService loadElasService;
    @Resource
    private CommentDao commentDao;

    public String fileUrl = "http://localhost:9091/file/";

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public MoveVo queryById(Integer id) {
        return copyEToVo(this.moveDao.selectById(id));
    }

    @Override
    public PageInfo<MoveVo> hot(Integer page, Integer size) {
        PageHelper.startPage(page, size);
        LambdaQueryWrapper<Move> wrapper = new LambdaQueryWrapper<>();
        List<Move> list = new ArrayList<>();
        list = moveDao.selectByScore();
        list.forEach(move -> {
            log.info("{}", move.getScore());
        });
        final List<MoveVo> moveVos = copyList(list).stream().sorted(Comparator.comparing(MoveVo::getScore).reversed()).collect(Collectors.toList());
        ;
        return SwapePageUtil.swapePage(list, moveVos);
    }

    @Override
    public MoveVo copyEToVo (Move entity){
        MoveVo moveVo = new MoveVo();
    if (!ObjectUtils.isEmpty(entity.getDouban().toString())){
    moveVo.setDouban(entity.getDouban().toString());
    }
        if (!ObjectUtils.isEmpty( entity.getPeople())) {

            moveVo.setPeopleCount(entity.getPeople());
        }
//        if (!ObjectUtils.isEmpty( entity.getImdb())) {
//        moveVo.setImdb(entity.getImdb());
//        }
        moveVo.setScore(entity.getScore());
        if (!ObjectUtils.isEmpty( entity.getPeople())) {

            moveVo.setPeopleCount(entity.getPeople());
        }
        moveVo.setMoveCount(entity.getMoveCount());


        BeanUtils.copyProperties(entity, moveVo);
        //组装 标签列表
        moveVo.setTagList(tagDao.selectTagListByMoveId(entity.getId()));
        //组装 演员列表
        moveVo.setActorList(actorDao.selectTagListByMoveId(entity.getId()));
        return moveVo;
    }

    @Override
    public Move update (Move move){
        this.moveDao.updateById(move);

//        if (!ObjectUtils.isEmpty(move.getName())) {
//            ESUtils.updateDocumentMap(move.getId(), move.getName());
//        }

        if (!ObjectUtils.isEmpty(move.getName())) {
          //  ESUtils.updateDocumentMap(move.getId(), move.getName());
        }

        return this.moveDao.selectById(move.getId());
    }


    @Override
    public boolean deleteById (Integer id){
//        try {
//          //  ESUtils.deleteDocument(id.toString());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return this.moveDao.deleteById(id) > 0;
    }

    /**
     * 分页查询
     *
     * @param page 页码
     * @param size 页大小
     * @return 查询结果
     */
    @Override
    public PageInfo<MoveVo> queryAll(Integer page, Integer size, String keyWord, Integer tag) {
        PageHelper.startPage(page, size);
        LambdaQueryWrapper<Move> wrapper = new LambdaQueryWrapper<>();
        List<Move> list = new ArrayList<>();
        list = moveDao.selectList(null);

        if (!ObjectUtils.isEmpty(tag)) {
            list.clear();
            List<Integer> moveIds = new ArrayList<>();
            if (tag == 1) {
                moveIds = moveTagDao.selectList(null).stream().map(MoveTag::getMoveId).collect(Collectors.toList());
            } else {
                moveIds = moveTagDao.selectList(new LambdaQueryWrapper<MoveTag>().eq(MoveTag::getTagId, tag)).stream().map(MoveTag::getMoveId).collect(Collectors.toList());
            }
            if (moveIds.size() != 0) {
                list = moveDao.selectBatchIds(moveIds);
            }
        }

        if (!ObjectUtils.isEmpty(keyWord)) {



            list.clear();
            List<Integer> ids = new ArrayList<>();
//            try {
//               // ids = loadElasService.testMatch(keyWord);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
            if(ids.size() != 0){
                wrapper.in(Move::getId, ids);
                list = this.moveDao.selectList(wrapper);
            }

        }


        return SwapePageUtil.swapePage(list, copyList(list));
    }









    public List<MoveVo> copyList (List < Move > list) {
        List listCopy = new ArrayList<MoveVo>();
        list.stream().parallel().forEach(move -> {
            listCopy.add(copyEToVo(move));
        });
        return listCopy;
    }

    @Override
    public Move insert(MoveAddVo moveAddVo) {
        final Move move = new Move();
        move.setDouban(Double.valueOf(moveAddVo.getDouban()));
        move.setImdb(moveAddVo.getImdb());
        BeanUtils.copyProperties(moveAddVo, move);
        this.moveDao.insert(move);
        move.setScore(0.0);
        move.setPeople(0);
        moveAddVo.getTagList().stream().parallel().forEach(tagId -> {
            MoveTag moveTag = new MoveTag();
            moveTag.setMoveId(move.getId());
            moveTag.setTagId(tagId);
            moveTagDao.insert(moveTag);
        });
        moveAddVo.getActorList().stream().parallel().forEach(actorId -> {
            final MoveActor moveActor = new MoveActor();
            moveActor.setMoveId(move.getId());
            moveActor.setActorId(actorId);
            moveActorDao.insert(moveActor);
        });
      //  ESUtils.insertDocument(move.getId(), move.getName());
        return move;
    }
}
